package com.ldfile.server.config;

import com.ldfile.server.exception.FileServerException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author callmecool.ldsoft
 * @description tools
 * @since 2020/8/3 23:14
 */
@Configuration
@RequestMapping("config")
public class FileServiceInfoConfiguration {
    @Value("${file.upload.dir}")
    private String dirYml;

    @Value("${file.upload.url}")
    private String urlYml;

    @Value("${file.upload.path}")
    private String pathYml;

    public String getDirYml() {
        // 如果文件保存路径为空则将 当前工作目录作 + File.separator + FileServer 为保存路径
        if (StringUtils.isEmpty(dirYml)) {
            dirYml = System.getProperty("user.dir") + File.separator + "FileServer";
        }
        return dirYml;
    }

    public String getPathYml() {
        // 如果url内的path为空则默认为file-server
        if (StringUtils.isEmpty(pathYml)) {
            pathYml = "/file-server";
        }
        return pathYml;
    }

    public String getUrlYml() throws FileServerException {
        if(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) == null){
            throw new FileServerException("网络连接失败！") ;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            // 如果url为空则获取服务器的ip跟端口号
            if (StringUtils.isEmpty(urlYml)) {
                urlYml = request.getScheme() + "://" + request.getServerName();
            }
        }catch (Exception e){
            throw new FileServerException(e.getMessage()) ;
        }
        return urlYml;
    }
}
